const router = require('koa-router')()
const sequelize = require('../../dbHelper/db')
const { sys_role: RoleModel, sys_role_menu, sys_menu } = require('../../dbHelper/db').models
const { Op } = require('sequelize')

router.prefix('/role')

router.get('/getRoleList', async(ctx) => {
  const roleList = await RoleModel.findAll({
    include: [
      {
        model: sys_menu,
        attributes: ['menu_id']
      }
    ],
    where: {
      del_flag: {
        [Op.eq]: 0
      }
    }
  })

  for (let i = 0; i < roleList.length; i++) {
    roleList[i] = roleList[i].toJSON()

    roleList[i].menu_ids = roleList[i].sys_menus.map(obj => obj.menu_id)
    delete roleList[i].sys_menus
  }

  ctx.body = {
    code: 0,
    data: roleList,
    msg: 'ok'
  }
})

router.get('/getRoleInfoById', async(ctx) => {
  const query = ctx.request.query

  let objRole = await RoleModel.findByPk(query.role_id, {
    include: [
      { model: sys_menu, attributes: ['menu_id'] }
    ]
  })

  if (objRole) {
    objRole = objRole.toJSON()
    objRole.menu_ids = objRole.sys_menus.map(obj => obj.menu_id)
    delete objRole.sys_menus
  }

  ctx.body = {
    code: 0,
    data: objRole,
    msg: 'ok'
  }
})

router.get('/getActiveRoles', async(ctx) => {
  const roleList = await RoleModel.findAll({
    where: {
      del_flag: 0,
      status: 0
    }
  })

  ctx.body = {
    code: 0,
    data: roleList,
    msg: 'ok'
  }
})

router.post('/addRole', async(ctx) => {
  // 请求参数校验
  ctx.verifyParams({
    role_key: { type: 'string', required: true },
    role_name: { type: 'string', required: true },
    role_sort: { type: 'number', required: true },
    status: { type: 'enum', values: [0, 1] }
  })

  const { role_key, role_name, role_sort, status, remark, meau_ids } = ctx.request.body

  let objRole = await RoleModel.findOne({
    where: {
      [Op.or]: [
        { role_key },
        { role_name }
      ]
    }
  })

  if (objRole) {
    ctx.body = {
      code: -1,
      msg: '岗位名称或岗位ID重复，创建失败！'
    }
  } else {
    const t = await sequelize.transaction()

    try {
      objRole = await RoleModel.create({
        role_key,
        role_name,
        role_sort,
        status,
        remark: remark || ''
      }, { transaction: t })

      if (Array.isArray(meau_ids)) {
        const insertSql = meau_ids.map((menu_id) => {
          return {
            role_id: objRole.role_id,
            menu_id: menu_id
          }
        })

        await sys_role_menu.bulkCreate(insertSql, { transaction: t })
      }

      t.commit()

      ctx.body = {
        code: 0,
        msg: '创建成功！',
        data: objRole
      }
    } catch (error) {
      t.rollback()
    }
  }
})

router.put('/modifyRole', async(ctx) => {
  // 请求参数校验
  ctx.verifyParams({
    role_key: { type: 'string', required: true },
    role_name: { type: 'string', required: true },
    role_sort: { type: 'number', required: true },
    status: { type: 'enum', values: [0, 1] }
  })

  const params = ctx.request.body

  const otherRole = await RoleModel.findOne({
    where: {
      role_id: {
        [Op.ne]: params.role_id
      },
      [Op.or]: {
        role_key: params.role_key,
        role_name: params.role_name
      }
    }
  })

  if (otherRole) {
    ctx.body = {
      code: -1,
      msg: '角色名称或角色标识重复，不能修改！'
    }
  } else {
    const t = await sequelize.transaction()

    try {
      await RoleModel.update({
        role_key: params.role_key,
        role_name: params.role_name,
        role_sort: params.role_sort,
        status: params.status,
        remark: params.remark
      }, {
        where: {
          role_id: params.role_id
        },
        transaction: t
      })

      await sys_role_menu.destroy({
        where: {
          role_id: params.role_id
        },
        transaction: t
      })

      const meau_ids = params.meau_ids

      if (Array.isArray(meau_ids)) {
        const insertSql = meau_ids.map((menu_id) => {
          return {
            role_id: params.role_id,
            menu_id: menu_id
          }
        })

        await sys_role_menu.bulkCreate(insertSql, {
          transaction: t
        })
      }

      t.commit()

      ctx.body = {
        code: 0,
        msg: '修改成功！'
      }
    } catch (e) {
      t.rollback()
    }
  }
})

router.delete('/deleteRole', (ctx) => {
  const query = ctx.request.query

  if (query.role_id === undefined) {
    ctx.body = {
      code: -1,
      msg: '参数错误'
    }
    return
  }

  RoleModel.update({
    del_flag: 2
  }, {
    where: {
      role_id: query.role_id
    }
  })

  ctx.body = {
    code: 0,
    msg: '删除成功！'
  }
})

module.exports = router
